<template>
  <div class="invite-wrapper">
    <div>
      <a-card title="邀请好友" hoverable>
        <p>
          欢迎使用我们的“邀请推广”功能！现在，您可以通过邀请您的朋友、家人或同事来推广我们的网站，并赚取一些额外的奖励。
        </p>
        <p>现在，点击并生成您的邀请码，并分享给您的好友吧！</p>
      </a-card>
    </div>
    <div class="invite-code-control">
      <a-card title="邀请码管理">
        <template #extra>
          <a-button type="primary" @click="handleGenerateCode">点击生成邀请码</a-button>
        </template>
        <a-list>
          <template v-for="item in codeList" :key="item.key">
            <a-list-item>
              <div class="invite-code-item">
                <div class="invite-code">
                  <span>{{ item.code }}</span>
                  <a-button type="link" size="small" @click="handleCopy(item.code)">
                    <copy-outlined />
                  </a-button>
                </div>
                <div class="code-time">创建时间：{{ item.time }}</div>
              </div>
              <template #actions>
                <!--删除-->
                <a-popconfirm
                  title="确认删除吗？"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="handleDelete(item.code)"
                >
                  <a-button type="link" danger>删除</a-button>
                </a-popconfirm>
              </template>
            </a-list-item>
          </template>
        </a-list>
      </a-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { CopyOutlined } from '@ant-design/icons-vue';
import { toClipboard } from '@soerenmartius/vue3-clipboard';
import { notification } from 'ant-design-vue';
import { onBeforeMount, onMounted, ref } from 'vue';
type CodeObj = {
  code: string;
  time: string;
  key: string;
};
const codeList = ref<CodeObj[]>([]);
onBeforeMount(() => {
  let list = localStorage.getItem('inviteCode');
  if (list === null || list.length === 0) {
    // 随机生成6位字符串
    let code = Math.random().toString(36).substr(2, 6);
    // 获取当前时间并格式化
    let date = new Date();
    let time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    // 随机生成key
    let key = Math.random().toString(36).substr(2, 6);
    let codeObj = {
      code,
      time,
      key,
    };
    localStorage.setItem('inviteCode', JSON.stringify([codeObj]));
  }
});
onMounted(() => {
  let list = localStorage.getItem('inviteCode');
  if (list !== null) {
    codeList.value = JSON.parse(list);
  }
});

const handleDelete = (val: string) => {
  console.log(val);
  let list = localStorage.getItem('inviteCode');
  if (list !== null) {
    codeList.value = codeList.value.filter((item: CodeObj) => item.code !== val);
    localStorage.setItem('inviteCode', JSON.stringify(codeList.value));
    notification.success({
      message: '提示',
      description: '删除成功！',
    });
  } else {
    notification.error({
      message: '提示',
      description: '删除失败！',
    });
  }
};

const handleCopy = (val: string) => {
  let url = window.location.href;
  // 去除后缀
  url = url.substring(0, url.lastIndexOf('/'));
  const str = `快来加入这个有趣的知识星球吧！${url}我的邀请码是：${val}`;
  toClipboard(str);
  notification.success({
    message: '提示',
    description: '复制成功，快去分享给好友吧！',
  });
};

const handleGenerateCode = () => {
  let list = localStorage.getItem('inviteCode');
  if (list !== null) {
    // 随机生成6位字符串
    let code = Math.random().toString(36).substr(2, 6);
    // 获取当前时间并格式化
    let date = new Date();
    let time = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    let codeObj = {
      code,
      time,
      key: Math.random().toString(36).substr(2, 6),
    };
    codeList.value.push(codeObj);
    localStorage.setItem('inviteCode', JSON.stringify(codeList.value));
    notification.success({
      message: '提示',
      description: '生成成功！',
    });
  }
};
</script>

<style lang="less" scope>
.invite-wrapper {
  margin: 12px;
  min-height: calc(100vh - 136px);
  min-width: calc(100vw - 258px);
  .invite-code-control {
    margin-top: 20px;
    .invite-code-item {
      width: 100%;
      display: flex;
      justify-content: space-between;
      .invite-code {
        font-size: 16px;
      }
      .code-time {
        font-size: 14px;
      }
    }
  }
}
</style>
